import React from 'react';
import { connect } from 'dva';
import {
  Form,
  Card,
  Row,
  Col,
  Select,
  Input,
  Button,
  Icon,
  Tag,
  Modal,
  Divider,
  Dropdown,
  Menu,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';
import TableList from '@/components/TableList';
// import pageListHelp from '@/utils/pageListHelp';
import Add from './Tasks/Add';
import Edit from './Tasks/edit';
import Detail from './Tasks/detail';

@connect(
  state => ({
    loadingqueryPageList: state.loading.effects['taskMngt/queryPageList'],
    loadingqueryResExecutionCycleTypeList:
      state.loading.effects['taskMngt/queryResExecutionCycleTypeList'],
    dataqueryPageList: state.taskMngt.dataqueryPageList,
    dataqueryResExecutionCycleTypeList: state.taskMngt.dataqueryResExecutionCycleTypeList,
  }),
  dispatch => ({
    queryPageList: e => dispatch({ type: 'taskMngt/queryPageList', payload: e }),
    queryResExecutionCycleTypeList: e =>
      dispatch({ type: 'taskMngt/queryResExecutionCycleTypeList', payload: e }),
    immediateExecuteTask: e => dispatch({ type: 'taskMngt/immediateExecuteTask', payload: e }),
    deleteByIds: e => dispatch({ type: 'taskMngt/deleteByIds', payload: e }),
    setTaskStatus: e => dispatch({ type: 'taskMngt/setTaskStatus', payload: e }),
  })
)
@Form.create({ name: 'AuditTask' })
export default class AuditTask extends React.Component {
  state = {
    selectedRows: [],
  };
  columns = [
    {
      title: '任务名称',
      dataIndex: 'executionPolicyName',
      ellipsis: true,
    },
    {
      title: '行数',
      dataIndex: 'lineNumber',
      ellipsis: true,
    },
    // {
    //   title: '任务类型',
    //   dataIndex: 'executionPolicyType',
    //   ellipsis: true,
    //   render: executionPolicyType =>
    //     (
    //       [
    //         { executionPolicyType: 1, auditTaskTypeName: '全量/增量' },
    //         { executionPolicyType: 2, auditTaskTypeName: '抽样' },
    //       ].find(item => item.executionPolicyType == executionPolicyType) || {}
    //     ).auditTaskTypeName,
    // },
    {
      title: '执行周期',
      dataIndex: 'executionCycleTypeId',
      ellipsis: true,
      render: (executionCycleTypeId, ctx) => {
        const value = (
          [
            {
              cycleTypeId: 1,
              cycleTypeCode: 'NOW_PERFORM',
              cycleTypeName: '立即执行',
            },
            {
              cycleTypeId: 2,
              cycleTypeCode: 'TIMING_PERFORM',
              cycleTypeName: '定时执行',
            },
            {
              cycleTypeId: 4,
              cycleTypeCode: 'WEEK_PERFORM',
              cycleTypeName: '按周执行',
            },
            {
              cycleTypeId: 5,
              cycleTypeCode: 'MONTH_PERFORM',
              cycleTypeName: '按月执行',
            },
            {
              cycleTypeId: 7,
              cycleTypeCode: 'PERIODIC_PERFORM',
              cycleTypeName: '周期执行',
            },
          ].find(item => item.cycleTypeId == executionCycleTypeId) || {}
        ).cycleTypeName;
        const executionDay =
          {
            4: `/${
              ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][
                ctx.executionDay
              ]
            }`,
            5: `/${ctx.executionDay}号`,
            6: `/第${ctx.executionDay}天`,
            7: `/每隔${ctx.executionDay}天`,
          }[ctx.executionCycleTypeId] || '';
        const executionTime = ctx.executionCycleTypeId != 1 ? `/${ctx.executionTime}` : '';
        return value + executionDay + executionTime;
      },
    },
    {
      title: '任务状态',
      dataIndex: 'taskStatus',
      ellipsis: true,
      render: text => [<Tag color="green">启用</Tag>, <Tag color="red">停用</Tag>][text] || text,
    },
    {
      title: '创建人',
      dataIndex: 'createUserCode',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'executionPolicyId',
      width: 255,
      render: (executionPolicyId, ctx) => (
        <>
          <Detail executionPolicyId={executionPolicyId}>
            <a>详情</a>
          </Detail>
          {!ctx.taskStatus ? (
            <>
              <Divider type="vertical" />
              <a onClick={() => this.immediateExecuteTask(executionPolicyId)}>立即执行</a>
            </>
          ) : null}
          <Divider type="vertical" />
          <a
            onClick={() =>
              this.props.history.push(
                '/taskInfo/taskHistory?executionPolicyId=' + executionPolicyId
              )
            }
          >
            执行历史
          </a>
          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item>
                  <Edit executionPolicyId={executionPolicyId} pageList={this.pageList.bind(this)}>
                    编辑
                  </Edit>
                </Menu.Item>
                {['停用', '启用'][ctx.taskStatus] ? (
                  <Menu.Item>
                    <a onClick={() => this.setTaskStatus(executionPolicyId, ctx.taskStatus)}>
                      {['停用', '启用'][ctx.taskStatus]}
                    </a>
                  </Menu.Item>
                ) : null}
                <Menu.Item>
                  <a onClick={() => this.deleteData(executionPolicyId)}>删除</a>
                </Menu.Item>
              </Menu>
            }
          >
            <a>
              更多
              <Icon type="down" />
            </a>
          </Dropdown>
        </>
      ),
    },
  ];
  immediateExecuteTask = data => {
    Modal.confirm({
      title: '执行',
      content: '您确认要执行选择的任务吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () =>
        this.props
          .immediateExecuteTask({
            executionPolicyId: data,
          })
          .then(res => {
            if (res.rescode == 200) {
              this.props.history.push('/taskInfo/taskHistory');
            } else if (res.rescode == 205) {
              Modal.warning({ title: '操作告警', content: res.msg });
            } else {
              Modal.error({ title: '操作失败', content: res.msg });
            }
          }),
    });
  };
  deleteData = data => {
    Modal.confirm({
      title: '删除',
      content: '您确认要删除选择的任务吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () =>
        this.props
          .deleteByIds({
            executionPolicyIds: data,
          })
          .then(res => {
            if (res.rescode == 200) {
              Modal.success({ title: res.msg });
              this.setState({ selectedRows: [] });
              this.pageList();
            } else if (res.rescode == 205) {
              Modal.warning({ title: '操作告警', content: res.msg });
            } else {
              Modal.error({ title: '操作失败', content: res.msg });
            }
          }),
    });
  };
  setTaskStatus = (data, taskStatus) => {
    Modal.confirm({
      title: taskStatus == 0 ? '停用' : '启用',
      content: `您确认要${taskStatus == 0 ? '停用' : '启用'}选择的任务吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () =>
        this.props
          .setTaskStatus({
            executionPolicyId: data,
            taskStatus: taskStatus == 0 ? 1 : 0,
          })
          .then(res => {
            if (res.rescode == 200) {
              Modal.success({ title: res.msg });
              this.setState({ selectedRows: [] });
              this.pageList();
            } else if (res.rescode == 205) {
              Modal.warning({ title: '操作告警', content: res.msg });
            } else {
              Modal.error({ title: '操作失败', content: res.msg });
            }
          }),
    });
  };
  pageList(pageSize = 10, pageNum = 0) {
    const params = {
      ...this.state.fieldsValue,
      pageSize: this.state.pagination ? this.state.pagination.pageSize : pageSize,
      pageNum: this.state.pagination ? this.state.pagination.current - 1 : pageNum,
    };
    this.props.queryPageList(params);
  }
  handleStandardTableChange(pagination) {
    this.setState({ pagination }, this.pageList);
  }
  handleSearch = e => {
    e.preventDefault();
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState(
        {
          fieldsValue,
          pagination: '',
        },
        this.pageList
      );
    });
  };
  componentDidMount() {
    this.props.queryResExecutionCycleTypeList();
    this.pageList();
  }
  // componentDidUpdate(prevProps) {
  //   pageListHelp('dataqueryPageList', prevProps, this);
  // }
  render() {
    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              <Form onSubmit={this.handleSearch} layout="inline">      
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>       
                  <Col md={7} sm={24}>
                    <Form.Item label="任务名称">
                      {this.props.form.getFieldDecorator('executionPolicyName')(
                        <Input allowClear placeholder="请输入" />
                      )}
                    </Form.Item>
                  </Col>
                  {/* <Col md={8} sm={24}>
                    <Form.Item label="任务类型">
                      {this.props.form.getFieldDecorator('executionPolicyType')(
                        <Select allowClear placeholder="请选择">
                          <Select.Option value="">全部</Select.Option>
                          {[
                            { executionPolicyType: 1, auditTaskTypeName: '全量/增量' },
                            { executionPolicyType: 2, auditTaskTypeName: '抽样' },
                          ].map(item => (
                            <Select.Option
                              key={item.executionPolicyType}
                              value={item.executionPolicyType}
                            >
                              {item.auditTaskTypeName}
                            </Select.Option>
                          ))}
                        </Select>
                      )}
                    </Form.Item>
                  </Col>                  */}
                  <Col md={6} sm={24}>
                    <Form.Item label="执行周期">
                      {this.props.form.getFieldDecorator('executionCycleTypeId')(
                        <Select
                          allowClear
                          placeholder="请选择"
                          // loading={this.props.loadingqueryResExecutionCycleTypeList}
                        >
                          <Select.Option value="">全部</Select.Option>
                          {[
                            {
                              cycleTypeId: 1,
                              cycleTypeCode: 'NOW_PERFORM',
                              cycleTypeName: '立即执行',
                            },
                            {
                              cycleTypeId: 2,
                              cycleTypeCode: 'TIMING_PERFORM',
                              cycleTypeName: '定时执行',
                            },
                            {
                              cycleTypeId: 4,
                              cycleTypeCode: 'WEEK_PERFORM',
                              cycleTypeName: '按周执行',
                            },
                            {
                              cycleTypeId: 5,
                              cycleTypeCode: 'MONTH_PERFORM',
                              cycleTypeName: '按月执行',
                            },
                            {
                              cycleTypeId: 7,
                              cycleTypeCode: 'PERIODIC_PERFORM',
                              cycleTypeName: '周期执行',
                            },
                          ].map(item => (
                            <Select.Option key={item.cycleTypeId} value={item.cycleTypeId}>
                              {item.cycleTypeName}
                            </Select.Option>
                          ))}
                        </Select>
                      )}
                    </Form.Item>
                  </Col>                 
                  <Col md={6} sm={24}>
                    <Form.Item label="任务状态">
                      {this.props.form.getFieldDecorator('taskStatus')(
                        <Select allowClear placeholder="请选择">
                          <Select.Option value="">全部</Select.Option>
                          <Select.Option value={0}>启用</Select.Option>
                          <Select.Option value={1}>停用</Select.Option>
                        </Select>
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={5} sm={24}>
                    <span className={styles.submitButtons}>
                      <Button type="primary" htmlType="submit">
                        查询
                      </Button>
                      <Button
                        style={{ marginLeft: 8 }}
                        onClick={() => this.props.form.resetFields()}
                      >
                        重置
                      </Button>                      
                    </span>
                  </Col> 
                  </Row>              
              </Form>
            </div>
            <div className={styles.tableListOperator}>
              <Add pageList={() => this.pageList()}>
                <Button icon="plus" type="primary">
                  新增
                </Button>
              </Add>
              {this.state.selectedRows.length > 0 && (
                <span>
                  <Button onClick={() => this.deleteData(this.state.selectedRows)}>批量删除</Button>
                </span>
              )}
            </div>
          </div>
          <TableList
            size="middle"
            selectedRows={this.state.selectedRows}
            loading={this.props.loadingqueryPageList}
            data={this.props.dataqueryPageList}
            columns={this.columns}
            rowSelection={{
              selectedRowKeys: this.state.selectedRows,
              onChange: e => this.setState({ selectedRows: e }),
            }}
            onChange={pagination => this.handleStandardTableChange(pagination)}
            rowKey="executionPolicyId"
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}
